<script>
import {defineComponent, reactive, toRefs, onMounted, ref} from "vue";
import TabCard from "../../../components/TabCard.vue";
import ConfigItem from "../../../components/ConfigItem.vue";
import ConfigInput from "../../../components/ConfigInput.vue";
import ModuleCard from "../../../components/ModuleCard.vue";
import DefaultButton from "../../../components/DefaultButton.vue";
import ValidateCheck from "../../../components/ValidateCheck.vue";
import ConfigCombo from "../../../components/ConfigCombo.vue";
import ConfigCheck from "../../../components/ConfigCheck.vue";
import {
  getConfigList,
  editNetworkTcpIp,
  editNetworkPort,
  getNetWorkInfos,
  editNetworkGB,
  autoDHCP,
  restartSystem,
  ipIsAble,
  getGBInfo,
  setGBInfo,
  getIpv4Info,
  getIsAble,
} from "@/api/configure.js";

export default defineComponent({
  components: {
    TabCard,
    ConfigItem,
    ConfigInput,
    ModuleCard,
    DefaultButton,
    ValidateCheck,
    ConfigCombo,
    ConfigCheck,
  },
  setup() {
    //密码验证
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (state.GBForm1.rePassword !== "") {
          if (!GbElForm.value) return;
          GbElForm.value.validateField("rePassword");
        }
        callback();
      }
    };
    //确认密码验证
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认密码"));
      } else if (value !== state.GBForm1.password) {
        callback(new Error("确认密码不一致"));
      } else {
        callback();
      }
    };

    const state = reactive({
      currentTab: -1,
      isShow: false,
      tcpipForm: {
        deviceIpv4Addr: "",
        deviceIpv6Addr: "",
        dnsServer: "",
        // dnsServerBackup: "",
        ipv4Gateway: "",
        ipv4SubnetMask: "",
        ipv6: 0,
        ipv6Gateway: "",
        ipv6SubnetMask: "",
        mac: "",
        networkCardType: "eth0",
      },
      GBForm1: {
        heartbeat: 0,
        insertMethod: 0,
        localSipPort: "",
        maxHeartbeatTimeout: "",
        registerInterval: 0,
        registerLifespan: 0,
        registerStatus: 0,
        server: "",
        domain: "",
        sipServerId: "",
        port: "",
        id: "",
        number: "",
        streamIndex: 0,
        transportProtocol: 0,
        rePassword: ""
      },
      GBForm: {
        rePassword: "",
        server: "",
        number: "",
        password: "",
        port: "",
        domain: "",
        id: "",
      },
      portForm: {
        httpPort: "",
        rtspPort: "",
      },
      netWorkList: [
        {
          value: "eth0",
          label: "eth0",
        },
      ],
      ipv6List: [
        {
          value: 0,
          label: "手动设置",
        },
        {
          value: 1,
          label: "自动获取",
        },
        {
          value: 2,
          label: "路由公告",
        },
      ],
      insertoptions: [
        {
          label: "28181",
          value: 0,
        },
      ],
      transportoptions: [
        {
          label: "TCP",
          value: 0,
        },
        {
          label: "UDP",
          value: 1,
        },
      ],
      streamoptions: [
        {
          label: "主码流（定时）",
          value: 0,
        },
      ],
      useCheck: false,
      ONVIFCheck: 0,
      GbRules: {
        localSipPort: [
          // {
          //   required: true,
          //   message: "请输入本地SIP端口",
          //   trigger: "blur",
          // },
        ],
        sipServerId: [
          {
            required: true,
            message: "请输入SIP服务器ID",
            trigger: "blur",
          },
        ],
        sipServerField: [
          {
            required: true,
            message: "请输入SIP服务器域",
            trigger: "blur",
          },
        ],
        sipServerAddr: [
          {
            required: true,
            message: "请输入SIP服务器地址",
            trigger: "blur",
          },
        ],
        sipServerPort: [
          {
            required: true,
            message: "请输入SIP服务器端口",
            trigger: "blur",
          },
          // {
          //   pattern: /^[0-9]+$/,
          //   message: "请输入整数值",
          //   trigger: "blur",
          // },
          // {
          //   type: "number",
          //   max: 65535,
          //   min: 1024,
          //   message: "请在1024--65535之间输入",
          //   trigger: "blur",
          // },
        ],
        sipUserName: [
          {
            required: true,
            message: "请输入SIP用户名",
            trigger: "blur",
          },
        ],
        sipUserId: [
          // {
          //   required: true,
          //   message: "请输入SIP用户认证ID",
          //   trigger: "blur",
          // },
        ],
        password: [{validator: validatePass, trigger: "blur"}],
        rePassword: [{validator: validatePass2, trigger: "blur"}],
        registerLifespan: [
          // {
          //   required: true,
          //   message: "请输入注册有效期",
          //   trigger: "blur",
          // },
          // {
          //   pattern: /^[0-9]+$/,
          //   message: "请输入整数值",
          //   trigger: "blur",
          // },
          // {
          //   type: "number",
          //   max: 100000,
          //   min: 3600,
          //   message: "请在3600--100000之间输入",
          //   trigger: "blur",
          // },
        ],
        heartbeat: [
          // {
          //   required: true,
          //   message: "请输入心跳周期",
          //   trigger: "blur",
          // },
          // {
          //   pattern: /^[0-9]+$/,
          //   message: "请输入整数值",
          //   trigger: "blur",
          // },
          // {
          //   type: "number",
          //   max: 255,
          //   min: 5,
          //   message: "请在5--255之间输入",
          //   trigger: "blur",
          // },
        ],
        registerInterval: [
          // {
          //   required: true,
          //   message: "请输入注册间隔",
          //   trigger: "blur",
          // },
          // {
          //   pattern: /^[0-9]+$/,
          //   message: "请输入整数值",
          //   trigger: "blur",
          // },
          // {
          //   type: "number",
          //   max: 600,
          //   min: 60,
          //   message: "请在60--600之间输入",
          //   trigger: "blur",
          // },
        ],
        maxHeartbeatTimeout: [
          // {
          //   required: true,
          //   message: "请输入最大心跳超时次数",
          //   trigger: "blur",
          // },
          // {
          //   pattern: /^[0-9]+$/,
          //   message: "请输入整数值",
          //   trigger: "blur",
          // },
          // {
          //   type: "number",
          //   max: 255,
          //   min: 3,
          //   message: "请在3--255之间输入",
          //   trigger: "blur",
          // },
        ],
      },
      isAuto: false,
      ipFormAuto: {
        deviceIpv4Addr: "",
        deviceIpv6Addr: "",
        dnsServer: "",
        // dnsServerBackup: "",
        ipv4Gateway: "",
        ipv4SubnetMask: "",
        ipv6: 0,
        ipv6Gateway: "",
        ipv6SubnetMask: "",
        mac: "",
        networkCardType: "eth0",
      },
      ipFormConfig: {
        deviceIpv4Addr: "",
        deviceIpv6Addr: "",
        dnsServer: "",
        // dnsServerBackup: "",
        ipv4Gateway: "",
        ipv4SubnetMask: "",
        ipv6: 0,
        ipv6Gateway: "",
        ipv6SubnetMask: "",
        mac: "",
        networkCardType: "eth0",
      },
    });

    const GbElForm = ref(null);

    onMounted(() => {
      getConfig();
      getGB();
      // getNetWorks();
      getIPV4();
      getIPV4IsAble();
    });

    const getIPV4IsAble = () => {
      getIsAble().then((res) => {
        state.isAuto = res.data;
        if (res.data) {
          state.tcpipForm = state.ipFormAuto;
        } else {
          state.tcpipForm = state.ipFormConfig;
        }
      });
    };

    //保存Ip
    const saveIp = () => {
      if (state.isAuto) {
        autoDHCP().then(() => {
          getIpv4Info().then(res => {
            state.isShow = true;
            state.tcpipForm.dnsServer = res.data.DNSServers.split(" ")[1];
            const ipAddress = res.data['IPAddress']
            const ipInfo = ipAddress.trim()
            const ipArray = ipInfo.split(' ')
            state.tcpipForm.deviceIpv4Addr = ipArray[1]
            state.tcpipForm.ipv4SubnetMask = ipArray[4]
            state.tcpipForm.ipv4Gateway = ipArray[7]
            const mac = res.data['mac']
            const macInfo = mac.trim()
            const macArray = macInfo.split(' ')
            state.tcpipForm.mac = macArray[1]
          })
          // editNetworkTcpIp(state.tcpipForm).then(
          //     (res) => {},
          //     (err) => {}
          // );
        });
      } else {
        editNetworkTcpIp(state.tcpipForm).then(
            (res) => {
              if (res.code === 200) {
                ElMessage({
                  message: "保存成功",
                  type: "success",
                  offset: 400,
                });
                state.isShow = true;
              } else {
                ElMessage({
                  message: res.message,
                  type: "warning",
                });
              }
            },
            (err) => {
              ElMessage({
                message: err.message,
                type: "warning",
              });
            }
        );
      }
    };

    //保存端口号
    const savePort = () => {
      editNetworkPort(state.portForm).then(
          (res) => {
            if (res.code === 200) {
              ElMessage({
                message: "保存成功",
                type: "success",
                offset: 200,
              });
            } else {
              ElMessage({
                message: res.message,
                type: "warning",
              });
            }
          },
          (err) => {
            ElMessage({
              message: err.message,
              type: "warning",
            });
          }
      );
    };

    //保存GB
    const saveGB = () => {
      GbElForm.value.validate((valid) => {
        if (valid) {
          setGBInfo(state.GBForm1).then(
              (res) => {
                if (res.code === 200) {
                  ElMessage({
                    message: "保存成功",
                    type: "success",
                    offset: 200,
                  });
                } else {
                  ElMessage({
                    message: res.message,
                    type: "warning",
                  });
                }
              },
              (err) => {
                ElMessage({
                  message: err.message,
                  type: "warning",
                });
              }
          );
        } else {
          return false;
        }
      });
    };

    const saveOnvif = () => {
    };

    const handleTabCurrentChange = (e) => {
      state.currentTab = e;
    };

    //获取配置列表
    const getConfig = () => {
      getConfigList(0).then(
          (info) => {
            if (info.code === 200) {
              // state.tcpipForm = info.data.configNetworkTCPIP;
              state.ipFormConfig = info.data.configNetworkTCPIP;
              state.portForm = info.data.configNetworkPort;
            } else {
              ElMessage({
                message: info.message,
                type: "warning",
              });
            }
          },
          (err) => {
            ElMessage({
              message: err.message,
              type: "warning",
            });
          }
      );
    };

    //获取其他网卡信息
    const getNetWorks = () => {
      getNetWorkInfos().then(
          (info) => {
            if (info.code === 200) {
              info.data.forEach((item) => {
                let net = {
                  value: item.interfaceName,
                  label: item.interfaceName,
                };
                state.netWorkList.push(net);
              });
            } else {
              ElMessage({
                message: info.message,
                type: "warning",
              });
            }
          },
          (err) => {
            ElMessage({
              message: err.message,
              type: "warning",
            });
          }
      );
    };

    //自动获取地址
    const autoGet = () => {
      if (!state.isAuto) {
        // autoDHCP().then((res) => {
        //   // getIpv4Info().then((res) => {
        //   //   if (res.code === 200) {
        //   //     state.tcpipForm.dnsServer = res.data.DNSServers.split(" ")[1];
        //   //     state.tcpipForm.ipv4Gateway =
        //   //       res.data.DefaultGateway.split("\n")[0];
        //   //     state.tcpipForm.deviceIpv4Addr = res.data.IPAddress;
        //   //     state.tcpipForm.ipv4SubnetMask = res.data.SubnetMask;
        //   //   }
        //   // });
        //   state.tcpipForm.dnsServer = res.data.DNSServers.split(" ")[1];
        //   const ipAddress = res.data['IPAddress']
        //   const ipInfo = ipAddress.trim()
        //   const ipArray = ipInfo.split(' ')
        //   state.tcpipForm.deviceIpv4Addr = ipArray[1]
        //   state.tcpipForm.ipv4SubnetMask = ipArray[4]
        //   state.tcpipForm.ipv4Gateway = ipArray[7]
        //   const mac = res.data['mac']
        //   const macInfo = mac.trim()
        //   const macArray = macInfo.split(' ')
        //   state.tcpipForm.mac = macArray[1]
        //   // editNetworkTcpIp(state.tcpipForm).then(
        //   //     (res) => {},
        //   //     (err) => {}
        //   // );
        // });
      } else {
        // saveIp();
      }
    };

    const isAbleIP = () => {
      ipIsAble(state.tcpipForm.deviceIpv4Addr).then(
          (res) => {
            if (res.code === 200) {
              if (res.data === true) {
                ElMessage({
                  message: res.message,
                  type: "success",
                  offset: 200,
                });
              } else {
                ElMessage({
                  message: res.message,
                  type: "warning",
                  offset: 200,
                });
              }
            } else {
              ElMessage({
                message: res.message,
                type: "warning",
                offset: 200,
              });
            }
          },
          (err) => {
            ElMessage({
              message: err.message,
              type: "warning",
              offset: 200,
            });
          }
      );
    };

    //重启系统
    const reStart = () => {
      restartSystem().then(
          (info) => {
            if (info.code === 200) {
              ElMessage({
                message: "重启成功",
                type: "success",
                offset: 400,
              });
            } else {
              ElMessage({
                message: info.message,
                type: "warning",
              });
            }
          },
          (err) => {
            ElMessage({
              message: err.message,
              type: "warning",
            });
          }
      );
      state.isShow = false;
    };

    const getGB = () => {
      getGBInfo().then((res) => {
        console.log(res)
        state.GBForm1 = res.data;
        state.GBForm1.rePassword = res.data.password;
        state.GBForm1.id = res.data.id;
      });
    };

    const getIPV4 = () => {
      getIpv4Info().then((res) => {
        if (res.code === 200) {
          state.tcpipForm.dnsServer = res.data.DNSServers.split(" ")[1];
          const ipAddress = res.data['IPAddress']
          const ipInfo = ipAddress.trim()
          const ipArray = ipInfo.split(' ')
          state.tcpipForm.deviceIpv4Addr = ipArray[1]
          state.tcpipForm.ipv4SubnetMask = ipArray[4]
          state.tcpipForm.ipv4Gateway = ipArray[7]
          const mac = res.data['mac']
          const macInfo = mac.trim()
          const macArray = macInfo.split(' ')
          state.tcpipForm.mac = macArray[1]
          // editNetworkTcpIp(state.tcpipForm).then(
          //   (res) => {},
          //   (err) => {}
          // );
        }
      });
    };

    return {
      ...toRefs(state),
      handleTabCurrentChange,
      getConfig,
      saveIp,
      savePort,
      getNetWorks,
      saveGB,
      saveOnvif,
      validatePass,
      validatePass2,
      autoGet,
      isAbleIP,
      GbElForm,
      reStart,
    };
  },
});
</script>

<template>
  <div class="network-container">
    <tab-card
        :tabs="['TCP/IP', '端口', 'GB/T28181', 'ONVIF协议']"
        :default-index="0"
        @changeIndex="handleTabCurrentChange"
    >
      <template v-if="currentTab === 0">
        <config-item style="margin-left: 15px" title="网卡">
          <el-select
              v-model="tcpipForm.networkCardType"
              placeholder="Select"
              style="width: 340px"
          >
            <el-option
                v-for="item in netWorkList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </config-item>
        <config-item style="margin-left: 15px">
          <input v-model="isAuto" type="checkbox" @click="autoGet"/> 自动获取
        </config-item>
        <config-item style="margin-left: 15px" title="设备IPv4地址">
          <config-input v-model:value="tcpipForm.deviceIpv4Addr" :disabled="isAuto">
            <template #append>
              <button class="btntest" @click="isAbleIP">测试</button>
            </template>
          </config-input>
        </config-item>
        <config-item style="margin-left: 15px" title="IPv4子网掩码">
          <config-input v-model:value="tcpipForm.ipv4SubnetMask" :disabled="isAuto"/>
        </config-item>
        <config-item style="margin-left: 15px" title="IPv4默认网关">
          <config-input v-model:value="tcpipForm.ipv4Gateway" :disabled="isAuto"/>
        </config-item>
        <!-- <config-item style="margin-left: 15px" title="IPv6模式">
          <el-select
            v-model="tcpipForm.ipv6"
            placeholder="Select"
            style="width: 340px"
          >
            <el-option
              v-for="item in ipv6List"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </config-item> -->
        <!-- <config-item style="margin-left: 15px" title="设备IPv6地址">
          <config-input v-model:value="tcpipForm.deviceIpv6Addr" />
        </config-item>
        <config-item style="margin-left: 15px" title="IPv6子网掩码">
          <config-input v-model:value="tcpipForm.ipv6SubnetMask" />
        </config-item>
        <config-item style="margin-left: 15px" title="IPv6默认网关">
          <config-input v-model:value="tcpipForm.ipv6Gateway" />
        </config-item> -->
        <config-item style="margin-left: 15px" title="物理地址">
          <config-input v-model:value="tcpipForm.mac" disabled/>
        </config-item>
        <module-card title="DNS服务器配置">
          <config-item title="首选DNS服务器">
            <config-input v-model:value="tcpipForm.dnsServer" :disabled="isAuto"/>
          </config-item>
          <!-- <config-item title="备用DNS服务器">
            <config-input v-model:value="tcpipForm.dnsServerBackup" />
          </config-item> -->
        </module-card>
        <save-button @click="saveIp"/>
      </template>
      <template v-if="currentTab === 1">
        <config-item title="HTTP端口">
          <config-input v-model:value="portForm.httpPort"/>
        </config-item>
        <config-item title="RTSP端口">
          <config-input v-model:value="portForm.rtspPort"/>
        </config-item>
        <save-button @click="savePort"/>
      </template>
      <template v-if="currentTab === 2">
        <el-form
            class="form"
            ref="GbElForm"
            :rules="GbRules"
            :model="GBForm1"
            label-width="auto"
        >
          <div class="left">
            <el-form-item label="平台接入方式">
              <el-select v-if="GBForm1" v-model="GBForm1.insertMethod" placeholder="请选择">
                <el-option
                    v-for="item in insertoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="本地SIP端口" prop="localSipPort">
              <el-input v-if="GBForm1" v-model="GBForm1.localSipPort"/>
            </el-form-item>

            <el-form-item label="传输协议">
              <el-select
                  v-if="GBForm1"
                  v-model="GBForm1.transportProtocol"
                  placeholder="请选择"
              >
                <el-option
                    v-for="item in transportoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="SIP服务器ID" prop="sipServerId">
              <el-input v-model="GBForm1['sipServerId']"/>
            </el-form-item>
            <el-form-item label="SIP服务器域" prop="sipServerField">
              <el-input v-model="GBForm1['sipServerField']"
              />
            </el-form-item>
            <el-form-item label="SIP服务器地址" prop="sipServerAddr">
              <el-input v-model="GBForm1['sipServerAddr']"
              />
            </el-form-item>
            <el-form-item label="SIP服务器端口" prop="sipServerPort">
              <el-input v-model.number="GBForm1['sipServerPort']"
              />
            </el-form-item>
            <el-form-item label="SIP用户名" prop="sipUserName">
              <el-input v-model="GBForm1['sipUserName']"
              />
            </el-form-item>
            <el-form-item label="SIP用户认证ID" prop="sipUserId">
              <el-input v-model="GBForm1['sipUserId']"
              />
            </el-form-item>
          </div>

          <div class="right">
            <el-form-item label="密码" prop="password"
            >
              <el-input type="password" v-model="GBForm1.password"/>
            </el-form-item>
            <el-form-item label="密码确认" prop="rePassword">
              <el-input type="password" v-model="GBForm1.rePassword"
              />
            </el-form-item>
            <el-form-item label="注册有效期" prop="registerLifespan">
              <el-input v-model.number="GBForm1.registerLifespan"
              />
            </el-form-item>
            <el-form-item label="注册状态">
              <el-input disabled v-model="GBForm1.registerStatus"
              />
            </el-form-item>
            <el-form-item label="心跳周期" prop="heartbeat">
              <el-input v-model.number="GBForm1.heartbeat"
              />
            </el-form-item>
            <el-form-item label="28181码流索引">
              <el-select v-model="GBForm1.streamIndex" placeholder="请选择">
                <el-option
                    v-for="item in streamoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select
              >
            </el-form-item>
            <el-form-item label="注册间隔" prop="registerInterval">
              <el-input v-model.number="GBForm1.registerInterval"
              />
            </el-form-item>
            <el-form-item label="最大心跳超时次数" prop="maxHeartbeatTimeout"
            >
              <el-input v-model.number="GBForm1.maxHeartbeatTimeout"/>
            </el-form-item>
            <!-- <el-form-item label="编码ID">视频通道编码ID </el-form-item> -->
          </div>
        </el-form>
        <el-table
            v-if="GBForm1"
            size="small"
            :border="true"
            :data="GBForm1.encodingList"
            max-height="200"
            height="200"
        >
          <el-table-column prop="coding" label="通道号" width="180"/>
          <el-table-column prop="id" label="视频输入编码ID"/>
        </el-table>
        <save-button @click="saveGB"/>
      </template>
      <template v-if="currentTab === 3">
        <config-item title="开启ONVIF协议">
          <el-radio-group v-model="ONVIFCheck">
            <el-radio :value="0">开启</el-radio>
            <el-radio :value="1">关闭</el-radio>
          </el-radio-group>
        </config-item>
        <save-button @click="saveOnvif"/>
      </template>
    </tab-card>

    <el-dialog v-model="isShow" title="重启" width="500">
      <span>修改重启生效，是否立即重启</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShow = false">取消</el-button>
          <el-button type="primary" @click="reStart"> 确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.network-container {
  height: 100%;

  :deep .el-form--default {
    clear: both;
  }

  .left {
    float: left;
    margin-left: 100px;
  }

  .right {
    float: right;
    margin-right: 300px;
  }

  .btntest {
    width: 80px;
    height: 30px;
    font-size: 16px;
  }
}
</style>
